package orm

import (
	"filestore-rebuild/config"
	"fmt"
	"github.com/jinzhu/gorm"
	"log"
)

var db *gorm.DB

func GetDB() *gorm.DB {
	var err error
	if db == nil {
		user := config.File.MustValue("mysql", "user")
		password := config.File.MustValue("mysql", "password")
		ip := config.File.MustValue("mysql", "ip")
		database := config.File.MustValue("mysql", "database")
		port := config.File.MustValue("mysql", "port")
		connStr := fmt.Sprintf(
			"%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
			user, password, ip, port, database,
		)
		db, err = gorm.Open("mysql", connStr)
		if err != nil {
			log.Printf("database connect failed: %s\n", err.Error())
			return nil
		}

	}
	return db
}
